package com.carefree.system.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.carefree.common.core.PageUtils;
import com.carefree.common.core.QueryParam;
import com.carefree.common.emus.StatusCodeEnum;
import com.carefree.common.exception.BusinessException;
import com.carefree.system.common.utils.SecurityUtils;
import com.carefree.system.modules.admin.dao.RoleDao;
import com.carefree.system.modules.admin.entity.RoleEntity;
import com.carefree.system.modules.admin.entity.UserRoleEntity;
import com.carefree.system.modules.admin.service.RoleService;
import com.carefree.system.modules.admin.service.UserRoleService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 角色
 *
 * @author tengbin
 */
@Service("roleService")
public class RoleServiceImpl extends ServiceImpl<RoleDao, RoleEntity> implements RoleService {

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RoleDao roleDao;

    @Resource
    private SecurityUtils securityUtils;


    /**
     * 分页查询
     *
     * @param params 分页参数
     * @return
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<RoleEntity> queryWrapper = new QueryWrapper<>();

        String keyword = (String) params.get("keyword");
        if (StringUtils.isNoneBlank(keyword)) {
            queryWrapper.like("role_code", keyword).or().like("role_name", keyword);
        }

        IPage<RoleEntity> page = page(new QueryParam<RoleEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

    /**
     * 添加角色信息
     *
     * @param role
     * @return
     */
    @Override
    public boolean saveRoleData(RoleEntity role) {
        role.setCreator(securityUtils.getPrincipalForUserId());
        return save(role);
    }

    /**
     * 根据id启用或禁用角色
     *
     * @param id
     * @param status
     * @return
     */
    @Override
    public boolean activeOrInActiveById(Long id, Integer status) {
        if (Objects.isNull(id) || Objects.isNull(status)) {
            return false;
        }
        RoleEntity roleEntity = getById(id);

        if (Objects.nonNull(roleEntity)) {
            roleEntity.setStatus(status);
            return updateById(roleEntity);
        }
        return false;
    }

    /**
     * 根据用户id查询所有角色列表及已分配角色信息
     *
     * @param userId
     * @return
     */
    @Override
    public Map<String, Object> queryRolesByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            throw new BusinessException(StatusCodeEnum.DATA_ERROR);
        }
        List<Long> userRoleIds = Collections.emptyList();

        // 根据用户id查询出所有对应角色关系
        List<UserRoleEntity> userRoleList = userRoleService.list(new QueryWrapper<UserRoleEntity>().eq("user_id", userId));

        // 如果能查到数据,就遍历集合,取出集合中的roleId
        if (! CollectionUtils.isEmpty(userRoleList)) {
            userRoleIds = userRoleList.stream().map(UserRoleEntity::getRoleId).collect(Collectors.toList());
        }

        // 查询所有角色信息
        List<RoleEntity> allRoles = list();

        // 将查询到的数据存到map中,返回
        Map<String, Object> resultMap = new HashMap<>(2);
        resultMap.put("allRoles", allRoles);
        resultMap.put("userRoleIds", userRoleIds);

        return resultMap;
    }


    /**
     * 根据用户id查询对应角色信息
     *
     * @param userId
     * @return
     */
    @Override
    public List<RoleEntity> queryRoleInfoByUserId(Long userId) {
        if (Objects.isNull(userId)) {
            throw new BusinessException(StatusCodeEnum.DATA_ERROR);
        }
        return roleDao.selectRolesInfoByUserId(userId);
    }
}
